package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class DishController {

    @Autowired
    private DishService dishService;


    @Autowired
    private RedisTemplate redisTemplate;


    // H5菜品查询
    @GetMapping("/dish/list")
    public ResultInfo list(Long categoryId,Integer status){

        List<Dish> list =null;
        // 1.先查询redis缓存
        // 1-1 设置rediskey
        String dishKey = "dish_"+categoryId;
        // 1-2 判断key是否存在
        if (redisTemplate.hasKey(dishKey)) {
            // 存在，查询redis
            list = (List<Dish>) redisTemplate.opsForValue().get(dishKey);
        }else{
            // 2.不存在，查询数据库
            list = dishService.list(categoryId,status);
            // 2-1 同步到redis
            redisTemplate.opsForValue().set(dishKey,list);
        }
        // 3.返回结果
        return ResultInfo.success(list);

    }
}
